package swimv2gm.client.user;

import java.io.*;
import java.util.*;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swimv2gm.bl.util.UserData;
import swimv2gm.bl.session.FriendshipManager;

/**
 * Servlet che fornisce i dati della lista amici: amici confermati e richieste
 * inviate e ricevute ancora da confermare.
 * 
 * @author Gallesio Matteo
 */
public class FriendList extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		FriendshipManager man;
		try {
			man = (FriendshipManager)InitialContext.doLookup("FriendshipManager");
		} catch (NamingException e) {
			response.sendError(500);
			return;
		}

		Long uid = (Long)request.getSession().getAttribute("user");

		// forbid access if the user is not connected or is an administrator
		if (uid == null
				|| (request.getSession().getAttribute("admin") != null
				&& (Boolean)request.getSession().getAttribute("admin"))) {
			response.sendError(403);
			return;
		}

		List<UserData> received = man.getPendingFriendsData(uid,true);
		request.setAttribute("received",received);

		List<UserData> sent = man.getPendingFriendsData(uid,false);
		request.setAttribute("sent",sent);

		List<UserData> friends = man.getFriendsData(uid);
		request.setAttribute("friends",friends);

		request.getRequestDispatcher("friendList.jsp").forward(request,response);
	}

	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		doGet(request,response);
	}

}
